package com.redoor.app.stake.basicdata.service.impl;

import com.redoor.app.stake.basicdata.dao.BaseConstsMapper;
import com.redoor.app.stake.basicdata.model.BaseConsts;
import com.redoor.app.stake.basicdata.model.BaseConststype;
import com.redoor.app.stake.basicdata.model.constants.BasicDataRedisConstants;
import com.redoor.app.stake.basicdata.model.controllerModel.BaseConstsCriteria;
import com.redoor.app.stake.basicdata.service.BaseConstsService;

import com.redoor.app.stake.basicdata.service.BaseConststypeService;
import com.redoor.app.stake.common.utils.JsonUtils;
import com.redoornetwork.framework.data.redis.util.RedisUtils;
import com.redoornetwork.framework.mybatis.service.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by wangjunlei on 2018-03-04 14:13:22.
 */
@Service
public class BaseConstsServiceImpl extends AbstractService<BaseConsts, String> implements BaseConstsService {
    private Logger logger = LoggerFactory.getLogger(BaseConstsServiceImpl.class);

    @Autowired
    private BaseConstsMapper baseConstsMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private BaseConststypeService baseConststypeService;


    @Override
    public void initConstsToRedis() {
        redisUtils.remove(BasicDataRedisConstants.REDIS_BASE_CONSTS);

        List<BaseConststype> constypeList = baseConststypeService.findAll();

        for (BaseConststype type : constypeList) {
            String code = type.getCode();

            BaseConstsCriteria params = new BaseConstsCriteria();
            params.setCodeType(code);
            List<BaseConsts> consts = baseConstsMapper.findConstsByCondition(params);

            redisUtils.hset(BasicDataRedisConstants.REDIS_BASE_CONSTS,code, JsonUtils.toJson(consts), BasicDataRedisConstants.REDIS_OVER_TIME_DAY);
            logger.info("{} collect finished,size {}",code, consts.size());
        }

    }

    @Override
    public List<BaseConsts> getConstsList(String const_code) {
        List<BaseConsts> constsList;
        //获取redis中存储的常量列表，用于判断是否需要发送mq
        if(redisUtils.hHasKey(BasicDataRedisConstants.REDIS_BASE_CONSTS,const_code)){
            constsList = Arrays.asList(JsonUtils.readValue(redisUtils.hget(BasicDataRedisConstants.REDIS_BASE_CONSTS,const_code).toString(),BaseConsts[].class));
        } else {
            BaseConstsCriteria params = new BaseConstsCriteria();
            params.setCodeType(const_code);
            constsList = baseConstsMapper.findConstsByCondition(params);
            redisUtils.hset(BasicDataRedisConstants.REDIS_BASE_CONSTS,const_code, JsonUtils.toJson(constsList), BasicDataRedisConstants.REDIS_OVER_TIME_DAY);
        }
        return constsList;
    }
}
